package com.iraeta.service;

import cn.alibaba.open.param.*;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.ocean.rawsdk.ApiExecutor;
import com.iraeta.Config;
import com.iraeta.common.ServiceException;
import com.iraeta.dao.erp.BasicDataDao;
import com.iraeta.dao.main.MyconfigDao;
import com.iraeta.entity.main.Renyuanmapping;
import com.iraeta.entity.main.Srmmessage;
import com.iraeta.entity.main.erpinterface.BaseNode;
import com.iraeta.entity.main.erpinterface.DescFlexField;
import com.iraeta.entity.main.type.SrmMessageStatus;
import com.iraeta.entity.main.type.SrmMessageType;
import com.iraeta.service.basic.RenYuanMappingService;
import com.iraeta.service.basic.SrmmessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class ProcessMessageTask {
    private static final Logger logger = LoggerFactory.getLogger(ProcessMessageTask.class);
    @Autowired
    MyconfigDao myconfigDao;
    @Autowired
    Config config;
    @Autowired
    BasicDataDao basicDataDao;
    @Autowired
    SrmmessageService srmmessageService;
    @Autowired
    RenYuanMappingService renYuanMappingService;
    @Autowired
    ErpU9_Interface erpU9Interface;

    /*定时处理阿里的消息*/
    public void processSrmMessageLoop(){
        String processMsg = myconfigDao.selectByKey("processMsg").getItemvalue();
        if(!processMsg.equals("1")){
            return;
        }
        List<Srmmessage> srmmessageList = srmmessageService.ListCanProcessMsg();
        for (Srmmessage srmmessage : srmmessageList) {
            this.processSrmMessageOne(srmmessage);
        }
    }

    public void processSrmMessageOne(Srmmessage srmmessage){
        try {
            switch (srmmessage.getTypeid()){
                case SrmMessageType.caiGouOrder:
                    this.processCaiGouMsg(srmmessage);
                    break;
                case SrmMessageType.qingGouOrder:
                    this.processQingGouMsg(srmmessage);
                    break;
                case SrmMessageType.faHuoOrder:
                    this.processFaHuoMsg(srmmessage);
                    break;
                case SrmMessageType.shouHuoOrder:
                    this.processShouHuoMsg(srmmessage);
                    break;
                default:
                    throw new ServiceException("非法的消息类型");
            }
        }catch (Exception e){
            logger.error(srmmessage.getId() + "未知异常:" + e.getMessage());
            srmmessage.setErrormsg("未知异常:" + e.getMessage());
            srmmessage.setStatusid(SrmMessageStatus.processFail);
            srmmessageService.update(srmmessage);
        }
    }

    private void processCaiGouMsg(Srmmessage srmmessage){
        ApiExecutor apiExecutor = new ApiExecutor(config.serverHost, Integer.parseInt(config.httpPort), Integer.parseInt(config.httpsPort), config.appKey,config.appSercret);
        AlibabaCaigouProcurementOrderQueryProcurementOrderDetailParam param = new AlibabaCaigouProcurementOrderQueryProcurementOrderDetailParam();
        param.setProcurementOrderId(srmmessage.getOrderid());
        AlibabaCaigouProcurementOrderQueryProcurementOrderDetailResult result = apiExecutor.execute(param, config.token).getResult();
        if(result == null){
            throw new ServiceException("调用阿里接口未知错误");
        }
        if(!result.getSuccess()){
            throw new ServiceException("调用阿里接口失败:" + result.getMessage());
        }
        AlibabaProcurementApiIntegrationModelIntegrationProcurementOrderModel data = result.getData();
        AlibabaProcurementApiIntegrationModelIntegrationProcurementOrderEntryModel wuliaoModel = data.getProcurementOrderEntries()[0];
        String wuLiaoCode =  wuliaoModel.getMaterialCode() == null ? "" : wuliaoModel.getMaterialCode() ;

        //如果是未处理 或者处理失败但是orderData为空的
        if(srmmessage.getStatusid() == SrmMessageStatus.unProcess || (srmmessage.getStatusid() == SrmMessageStatus.processFail && StrUtil.isEmpty(srmmessage.getOrderdata())) ){
            if(wuLiaoCode.startsWith("ZB")){
                srmmessage.setCompanyname("ZB");
                srmmessage.setStatusid(SrmMessageStatus.processSuccess);
            }else if(wuLiaoCode.startsWith("GQ")){
                srmmessage.setCompanyname("GQ");
                srmmessage.setStatusid(SrmMessageStatus.processSuccess);
            }else if(wuLiaoCode.startsWith("JN")){
                srmmessage.setCompanyname("JN");
                srmmessage.setStatusid(SrmMessageStatus.getDataSrm);
            }
            srmmessage.setOrderdata(JSON.toJSONString(data));
            srmmessage.setErrormsg("");
            srmmessageService.update(srmmessage);
        }

        if(srmmessage.getCompanyname().equals("JN") && SrmMessageStatus.processSuccess != srmmessage.getStatusid()){
            String caiGouResData = this.caiGouDataToU9(data);
            srmmessage.setCdefine1(caiGouResData);  //接收U9返回的数据记录到系统中
            srmmessage.setStatusid(SrmMessageStatus.processSuccess);
            srmmessageService.update(srmmessage);
        }
    }

    //构造U9的post数据
    private String caiGouDataToU9(AlibabaProcurementApiIntegrationModelIntegrationProcurementOrderModel srmData){
        Renyuanmapping renyuanmapping = renYuanMappingService.getByALiAccount(srmData.getCreatorLoginId()); //1688的操作者账户  找U9的用户数据
        if(renyuanmapping == null){
            throw new ServiceException("1688账户:[" + srmData.getCreatorLoginId() + "], 未找到U9系统对应的用户");
        }
        HashMap<String, Object> supplierMap = basicDataDao.supplier(srmData.getSupplierName());
        if(supplierMap == null){
            throw new ServiceException("1688供应商:[" + srmData.getSupplierName() + "], 未找到U9系统对应的供应商");
        }

        HashMap<String,Object> caiGou = new HashMap<>();
        caiGou.put("ID", 0L);
        //caiGou.put("DocNo", "PO" + DateUtil.format(srmData.getGmtCreate(), "yyyyMMddHHmmss"));
        //caiGou.put("DocumentType", "1002108130102243");
        caiGou.put("DocumentType", "PO1");
        caiGou.put("BizType", 316);
        caiGou.put("BusinessDate", DateUtil.format(srmData.getGmtCreate(), "yyyy-MM-dd HH:mm:ss"));        //日期
        //caiGou.put("OtherID", "0");
        caiGou.put("IsPriceIncludeTax", true);
//        caiGou.put("TC", "1");
//        caiGou.put("AC", "1");
        caiGou.put("TC", "C001");
        caiGou.put("AC", "C001");
        caiGou.put("Memo", "1688对接数据");
        caiGou.put("DocStatus", 0);
        //caiGou.put("SubType", "-1");
        //订单来源 pm_poline的 srcdoctype 默认是0 请购是1

        //供应商
        HashMap<String, Object> supplierParamMap = new HashMap<>();
        supplierParamMap.put("ID", 0L);
        supplierParamMap.put("Code", supplierMap.get("Code"));
        supplierParamMap.put("Name", "");
        caiGou.put("Supplier", supplierParamMap);
        //PriceList map
        //caiGou.put("PriceList", new BaseNode());
        //DescFlexField
        DescFlexField DescFlexFieldMap = new DescFlexField();
        caiGou.put("DescFlexField", DescFlexFieldMap);
        //PurOper 员工
        HashMap<String, Object> PurOperMap = new HashMap<>();
        //PurOperMap.put("m_iD", Long.valueOf(renyuanmapping.getuId()));
        PurOperMap.put("m_iD", 0L);
        //PurOperMap.put("m_code", renyuanmapping.getuCode());
        PurOperMap.put("m_code", "1029");   //这个默认的潘聚琨
        //PurOperMap.put("m_name", renyuanmapping.getuName());
        PurOperMap.put("sysState", 0);
        caiGou.put("PurOper", PurOperMap);
        //PurDept 部门
        HashMap<String, Object> PurDeptMap = new HashMap<>();
        //PurDeptMap.put("m_iD", 1002107130022244L);
        PurDeptMap.put("m_iD", 0L);
        PurDeptMap.put("m_code", "0301");
        //PurDeptMap.put("m_name", "采购部");
        PurDeptMap.put("sysState", 0);
        caiGou.put("PurDept", PurDeptMap);

        HashMap<String, Object> RcvOrgDTOMap = new HashMap<>();
        //RcvOrgDTOMap.put("m_iD", 1002104250240399L);
        RcvOrgDTOMap.put("m_iD", 0L);
        RcvOrgDTOMap.put("m_code", "004");
        //RcvOrgDTOMap.put("m_name", "伊莱特（济宁）高端装备科技有限公司");
        RcvOrgDTOMap.put("m_name", "");
        RcvOrgDTOMap.put("sysState", 0);
        HashMap<String, Object> TaxScheduleMap = new HashMap<>();
        //TaxScheduleMap.put("m_iD", 1002104110213732L);
        TaxScheduleMap.put("m_iD", 0L);
        TaxScheduleMap.put("m_code", "YZ02");
        //TaxScheduleMap.put("m_name", "13%税率");
        TaxScheduleMap.put("m_name", "");
        TaxScheduleMap.put("sysState", 0);
        HashMap<String, Object> ConfirmTerm = new HashMap<>();
        //ConfirmTerm.put("m_iD", 1002104250350057L);
        ConfirmTerm.put("m_iD", 0L);
        ConfirmTerm.put("m_code", "YZ01");
        //ConfirmTerm.put("m_name", "立账条件");
        ConfirmTerm.put("m_name", "");
        ConfirmTerm.put("sysState", 0);
        HashMap<String, Object> PaymentTermMap = new HashMap<>();
        //PaymentTermMap.put("m_iD", 1002104250350063L);
        PaymentTermMap.put("m_iD", 0L);
        PaymentTermMap.put("m_code", "YZ01");
        //PaymentTermMap.put("m_name", "付款条件");
        PaymentTermMap.put("m_name", "");
        PaymentTermMap.put("sysState", 0);
        HashMap<String, Object> whMap = new HashMap<>();
        whMap.put("m_iD", 0L);
        whMap.put("m_code", "203");
        whMap.put("m_name", "");
        whMap.put("sysState", 0);

        String wuliao_prefix = myconfigDao.selectByKey("wuliao_prefix").getItemvalue();
        int prefixLen = wuliao_prefix.length();

        //料品数据
        List<HashMap<String,Object>> liaoPinMapList = new ArrayList<>();
        int lineNo = 10;
        for (AlibabaProcurementApiIntegrationModelIntegrationProcurementOrderEntryModel procurementOrderEntry : srmData.getProcurementOrderEntries()) {
            HashMap<String,Object> liaoPinMap = new HashMap<>();
            liaoPinMap.put("DocLineNo", lineNo);
            liaoPinMap.put("POLineID", 0);
            liaoPinMap.put("ReqQtyTU", procurementOrderEntry.getAmount());  //数量
            //liaoPinMap.put("ReqQtyTBU", procurementOrderEntry.getAmount());
            liaoPinMap.put("SupplierConfirmQtyTU", procurementOrderEntry.getAmount());
            //liaoPinMap.put("SupplierConfirmQtyTBU", procurementOrderEntry.getAmount());
            liaoPinMap.put("FinallyPriceTC",procurementOrderEntry.getPrecisionPia());  //含税单价
            liaoPinMap.put("IsPresent", procurementOrderEntry.getPresent());    //是否赠品
//            BigDecimal TotalMnyTC = new BigDecimal(procurementOrderEntry.getTotalCost());
//            liaoPinMap.put("TotalMnyTC", TotalMnyTC); //总价含税
//            BigDecimal NetMnyTC = new BigDecimal(procurementOrderEntry.getTpea());
//            liaoPinMap.put("NetMnyTC", NetMnyTC);    //总价未税
//            BigDecimal TotalTaxAC = TotalMnyTC.subtract(NetMnyTC);
//            liaoPinMap.put("TotalTaxAC", TotalTaxAC);   //税额
            liaoPinMap.put("Memo", "");    //描述
            //liaoPinMap.put("DemandCode", -1);    //需求分类
            liaoPinMap.put("DeliveryDate", DateUtil.format(procurementOrderEntry.getDeliveryDate(), "yyyy-MM-dd"));    //交期

            //Project object
            //liaoPinMap.put("Project", new BaseNode());
            //Seiban object
            //liaoPinMap.put("Seiban", new BaseNode());
            //Task object
            //liaoPinMap.put("Task", new BaseNode());
            //Mfc object
            //liaoPinMap.put("Mfc", new BaseNode());
            //ConfirmTerm object
            liaoPinMap.put("ConfirmTerm", ConfirmTerm);
            //TradePath object
            //liaoPinMap.put("TradePath", new BaseNode());
            //RequiredPerson object
            //liaoPinMap.put("RequiredPerson", new BaseNode());
            //RequiredDept object
            //liaoPinMap.put("RequiredDept", new BaseNode());
            //DescFlexField object
            //DescFlexField
            DescFlexField PODescFlexFieldMap = new DescFlexField();
            liaoPinMap.put("DescFlexField", PODescFlexFieldMap);
            //RcvOrgDTO object
            liaoPinMap.put("RcvOrgDTO", RcvOrgDTOMap);
            //TaxSchedule object
            liaoPinMap.put("TaxSchedule", TaxScheduleMap);
            //PaymentTerm object
            liaoPinMap.put("PaymentTerm", PaymentTermMap);
            //wh object
            liaoPinMap.put("Wh", whMap);

            String itemCode = procurementOrderEntry.getMaterialCode().substring(prefixLen);
            HashMap<String, Object> ItemMasterMap = basicDataDao.getItemMaster(itemCode);
            if(ItemMasterMap == null){
                throw new ServiceException("1688存货编码:[" + procurementOrderEntry.getMaterialCode() + "], 未找到U9系统对应的料品编码");
            }
            //ItemInfoNew object
//            HashMap<String, Object> itemInfoNewMap = new HashMap<>();
//            itemInfoNewMap.put("ItemCode", itemCode);
//            itemInfoNewMap.put("ItemName", procurementOrderEntry.getMaterialName());
//            itemInfoNewMap.put("ItemGrade", "-1");
//            itemInfoNewMap.put("ItemPotency", "-1");
//            itemInfoNewMap.put("ItemOpt1_Code", "");
//            liaoPinMap.put("ItemInfoNew", itemInfoNewMap);
            //itemInfo object
            HashMap<String, Object> itemInfoMap = new HashMap<>();
            //itemInfoMap.put("m_code", itemCode);
            itemInfoMap.put("m_code", itemCode);
            itemInfoMap.put("m_name", "");
            //itemInfoMap.put("sysState", 0);
            itemInfoMap.put("ItemGrade", "-1");
            itemInfoMap.put("ItemPotency", "-1");
            liaoPinMap.put("ItemInfo", itemInfoMap);

            liaoPinMapList.add(liaoPinMap);
            lineNo+=10;
        }
        caiGou.put("POLineDTOList", liaoPinMapList);

        List<HashMap<String, Object>> jsonList = new ArrayList<>();
        jsonList.add(caiGou);
        String caiGouBody = JSON.toJSONString(jsonList);
        String res = erpU9Interface.addCaiGou(renyuanmapping.getuCode(), caiGouBody);
        String id = res.split("\\|")[1];
        String purOper = myconfigDao.selectByKey("purOper").getItemvalue();    //业务员  1002108170000217
        if(!purOper.equals("1")){
            String purDept = "1002107130022244";    //部门
            basicDataDao.updateCaiGouOrder(Long.valueOf(id), purOper, purDept); //修改同步以后的采购订单数据
        }
        return res;
    }

    private void processQingGouMsg(Srmmessage srmmessage){
        if(srmmessage.getStatusid() == SrmMessageStatus.unProcess){
            srmmessage.setOrderdata("{}");
            srmmessage.setStatusid(SrmMessageStatus.getDataSrm);
            srmmessage.setErrormsg("");
            srmmessageService.update(srmmessage);
        }

    }
    private void processFaHuoMsg(Srmmessage srmmessage){
//        if(srmmessage.getStatusid() == SrmMessageStatus.getDataSrm){
//            ApiExecutor apiExecutor = new ApiExecutor(config.serverHost, Integer.parseInt(config.httpPort), Integer.parseInt(config.httpsPort), config.appKey,config.appSercret);
//            ComAlibabaProcurementBuyerSendGoodsServiceQuerySendGoodsNoteParam param = new ComAlibabaProcurementBuyerSendGoodsServiceQuerySendGoodsNoteParam();
//            param.setId(srmmessage.getId());
//            param.setNeedLogisticsInfo(false);
//            ComAlibabaProcurementBuyerSendGoodsServiceQuerySendGoodsNoteResult result = apiExecutor.execute(param, config.token).getResult();
//            if(result == null){
//                throw new RuntimeException("调用阿里接口未知错误");
//            }
//            if(!result.getSuccess()){
//                throw new RuntimeException("调用阿里接口失败:" + result.getMessage());
//            }
//            AlibabaProcurementApiSendgoodsIntegrationResultIntegrationSendGoodsNoteModel data = result.getData();
//            String orderData = JSON.toJSONString(data);
//            srmmessage.setOrderdata(orderData);
//            srmmessage.setStatusid(SrmMessageStatus.getDataSrm);
//            srmmessage.setErrormsg("");
//            srmmessageService.update(srmmessage);
//        }
        //todo data存储到erp
    }

    private void processShouHuoMsg(Srmmessage srmmessage){
//        if(srmmessage.getStatusid() != SrmMessageStatus.getDataSrm){
//            ApiExecutor apiExecutor = new ApiExecutor(config.serverHost, Integer.parseInt(config.httpPort), Integer.parseInt(config.httpsPort), config.appKey,config.appSercret);
//            ComAlibabaProcurementBuyerReceiveGoodsServiceQueryReceiveGoodsNoteParam param = new ComAlibabaProcurementBuyerReceiveGoodsServiceQueryReceiveGoodsNoteParam();
//            param.setId(srmmessage.getId());
//            ComAlibabaProcurementBuyerReceiveGoodsServiceQueryReceiveGoodsNoteResult result = apiExecutor.execute(param, config.token).getResult();
//            if(result == null){
//                throw new RuntimeException("调用阿里接口未知错误");
//            }
//            if(!result.getSuccess()){
//                throw new RuntimeException("调用阿里接口失败:" + result.getMessage());
//            }
//            AlibabaProcurementApiReceivegoodsIntegrationResultIntegrationReceiveGoodsNoteModel data = result.getData();
//            if(srmmessage.getStatusid() == SrmMessageStatus.unProcess || srmmessage.getStatusid() == SrmMessageStatus.fail ){   //如果第一次处理获取处理失败
//                String orderData = JSON.toJSONString(data);
//                srmmessage.setOrderdata(orderData);
//                srmmessage.setStatusid(SrmMessageStatus.getDataSrm);
//                srmmessage.setErrormsg("");
//                srmmessageService.update(srmmessage);
//            }
//        }
        //todo data存储到erp
    }
}
